<svelte:window>
Posted on 2023-04-28 by
henrikvilhelmberglundAnother Svelte special element is <svelte:window>.
Here we want to see the width and have it change whenever we resize the window. We also want to focus the search bar whenever we press ctrl+f.
Here it is normally without using svelte:window. Let's try to rewrite it using svelte:window>.
 Width: 0 
<script>
	import { browser } from "$app/environment";
	let innerWidth = 0;
	import { onMount } from "svelte";
	let searchBar;
	onMount(() => {
		innerWidth = window.innerWidth;
		function onResize() {
			innerWidth = window.innerWidth;
		}
		window.addEventListener("resize", onResize);
		return () => window.removeEventListener("resize", onResize);
	});
	onMount(() => {
		function onKeydown(event) {
			if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "f") {
				searchBar.focus();
				event.preventDefault();
			}
		}
		window.addEventListener("keydown", onKeydown);
		return () => window.removeEventListener("keydown", onKeydown);
	});
</script>
<input bind:this={searchBar} placeholder="Search for..." />
<div>
	Width: {innerWidth}
</div>
<style>
</style>
Svelte bindings (bind:) are usually two way bindings but here everything except scrollX and scrollY are readonly so effectively they are one way bindings.
Here is a list of the properties we can bind to:
- innerWidth
- innerHeight
- outerWidth
- outerHeight
- scrollX (not readonly)
- scrollY (not readonly)
- online — an alias for window.navigator.onLine